package com.atguigu.boot.converter;

import com.atguigu.boot.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 自定义的Converter
 */
public class GuiguMessageConverter implements HttpMessageConverter<Person> {

    // 能不能把输入的数据读入
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    // 能不能写
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        // 是不是person类型
        return clazz.isAssignableFrom(Person.class);
    }

    /**
     *
     * 获取所有支持的媒体类型
     * 服务器要统计所有MessageConverter都能写出哪些内容类型
     *
     * application/x-guigu
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/x-guigu");
    }

    //
    @Override
    public Person read(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    // 自定义协议数据的写出
    @Override
    public void write(Person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String data = person.getUserName()+";"+person.getAge()+";"+person.getBirth();
        outputMessage.getBody().write(data.getBytes(StandardCharsets.UTF_8));
    }
}
